package com.zy.tree;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtils {

  // 定义jackson对象
  private static final ObjectMapper MAPPER = new ObjectMapper();

  /**
   * 将对象转换成json字符串
   * @param obj 需转换的对象
   * @param  flag Json格式化标识（0-否，1-是）
   * @return
   */
  public static <T> String objectToJson(T obj, int flag) {
    if (obj == null) {
      return null;
    }
    try {
      String string;
      if (flag == 1) {
        string = obj instanceof String ? (String) obj : MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
      } else {
        string = obj instanceof String ? (String) obj : MAPPER.writeValueAsString(obj);
      }
      return string;
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 将json结果集转化为对象
   *
   * @param jsonData json数据
   * @param beanType 对象中的object类型
   * @return
   */
  public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
    try {
      T t = MAPPER.readValue(jsonData, beanType);
      return t;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 将json数据转换成pojo对象list
   * <p>Title: jsonToList</p>
   * <p>Description: </p>
   * @param jsonData
   * @param beanType
   * @return
   */
  public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    try {
      List<T> list = MAPPER.readValue(jsonData, javaType);
      return list;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }

  public static void main(String[] args) {
    System.out.println("测试字符串对象：" + objectToJson("hello world", 1));
  }

}